package com.example.demo.common;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-06-11
 * Time: 10:54
 */

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 *  统一的返回对象, 保底策略防止错误返回
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    // 使用增强返回类
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 1. 非 AjaxResult 类型
        if(body instanceof AjaxResult) return body;

        // 2. String 类型已经通过配置项剔除转换器

        // 3. 其他类型直接封装成 AjaxResult
        return AjaxResult.success(body);
    }
}
